import React, { useEffect, useState } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { Card, message, Spin, Steps, Button } from 'antd';
import { problemService } from '@/services/problemService';
import { Problem, ProblemStep } from '@/types/problem';
import BasicForm from './components/BasicForm';
import TestCaseForm from './components/TestCaseForm';
import ProblemDescription from '@/pages/share/problem/components/ProblemDescription';
import styles from './Edit.module.css';

const Edit: React.FC = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const contestId = searchParams.get('contest_id');
  
  const [loading, setLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState<ProblemStep>('basic');
  const [problemData, setProblemData] = useState<Partial<Problem>>({});

  useEffect(() => {
    if (id) {
      fetchProblem();
    }
  }, [id]);

  const fetchProblem = async () => {
    try {
      setLoading(true);
      const response = await problemService.getProblem(Number(id));
      setProblemData(response.data.data);
    } catch (error) {
      message.error('获取题目失败');
      navigate('/admin/problem/list');
    } finally {
      setLoading(false);
    }
  };

  const handleBasicFormSubmit = async (values: any) => {
    try {
      // 添加 contest_id 到提交的数据中
      const submitData = {
        ...values,
        contest_id: contestId ? Number(contestId) : null
      };

      if (id) {
        // 更新现有题目
        await problemService.updateProblem(Number(id), submitData);
        message.success('更新题目成功');
        // 更新本地problemData状态，确保预览时显示最新数据
        setProblemData(prev => ({ ...prev, ...submitData }));
      } else {
        // 创建新题目
        const response = await problemService.createProblem(submitData);
        message.success('创建题目成功');
        // 如果是创建新题目，更新problemData
        setProblemData(response.data.data);
        // 更新URL，添加新创建的题目ID
        const newUrl = contestId 
          ? `/admin/problem/edit/${response.data.data.id}?contest_id=${contestId}`
          : `/admin/problem/edit/${response.data.data.id}`;
        navigate(newUrl, { replace: true });
      }
      setCurrentStep('testcase');
    } catch (error) {
      message.error(id ? '更新题目失败' : '创建题目失败');
    }
  };

  const handleTestCaseFormSubmit = async (values: any) => {
    try {
      // 使用 problemData 中的 id 或 URL 参数中的 id
      const problemId = problemData.id || id;
      if (problemId) {
        await problemService.patchProblem(Number(problemId), values);
        message.success('更新测试用例成功');
        // 更新本地problemData状态，确保预览时显示最新数据
        setProblemData(prev => ({ ...prev, ...values }));
      }
      setCurrentStep('preview');
    } catch (error) {
      message.error('更新测试用例失败');
    }
  };

  const handlePreviewSubmit = async () => {
    try {
      message.success('题目保存成功');
      
      // 获取返回地址参数
      const returnUrl = searchParams.get('returnUrl');
      
      if (returnUrl) {
        // 如果有返回地址，则返回到指定地址
        navigate(returnUrl);
      } else if (contestId) {
        // 如果是从比赛模块进入，则返回到比赛题目管理页面
        navigate(`/admin/contest/${contestId}/problems`);
      } else {
        // 默认返回到题目列表
        navigate('/admin/problem/list');
      }
    } catch (error) {
      message.error('保存失败');
    }
  };

  const renderStepContent = () => {
    if (loading) {
      return (
        <div className={styles.loadingContainer}>
          <div style={{ textAlign: 'center' }}>
            <Spin size="large" />
            <div style={{ marginTop: 8 }}>加载中...</div>
          </div>
        </div>
      );
    }

    switch (currentStep) {
      case 'basic':
        return (
          <BasicForm
            initialValues={problemData}
            onSubmit={handleBasicFormSubmit}
          />
        );
      case 'testcase':
        return (
          <TestCaseForm
            initialValues={problemData}
            onSubmit={handleTestCaseFormSubmit}
          />
        );
      case 'preview':
        return (
          <div>
            <ProblemDescription problem={problemData as Problem} />
            <div style={{ marginTop: 24, textAlign: 'center' }}>
              <Button onClick={() => setCurrentStep('basic')} style={{ marginRight: 16 }}>
                返回修改
              </Button>
              <Button type="primary" onClick={handlePreviewSubmit}>
                完成
              </Button>
            </div>
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div className={styles.container}>
      <Card className={styles.card}>
        <Steps
          className={styles.steps}
          current={['basic', 'testcase', 'preview'].indexOf(currentStep)}
          items={[
            { title: '基本信息' },
            { title: '测试用例' },
            { title: '预览' },
          ]}
        />
        <div className={styles.stepContent}>
          {renderStepContent()}
        </div>
      </Card>
    </div>
  );
};

export default Edit; 